<script setup lang="ts">
import { ref, watch } from 'vue'
import { roleList } from '../../api/roles'
import { User, UserFilled } from '@element-plus/icons-vue'

interface Props {
  modelValue: string
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: ''
})

const emit = defineEmits<{
  (e: 'update:modelValue', val: string): void
}>()

const value = ref<string>('')

const list = ref<any[]>([])

const initData = () => {
  list.value = []
  roleList()
    .then((res: any) => {
      list.value = res
    })
    .finally(() => {
      list.value.unshift({
        roleName: '所有角色',
        roleId: ''
      })
    })
}
initData()

watch(
  () => props.modelValue,
  (newVal) => {
    value.value = newVal
  },
  {
    immediate: true
  }
)

const handleClick = (val: any) => {
  value.value = val.roleId
  emit('update:modelValue', val.roleId)
}
</script>

<template>
  <div class="role-picker-wrapper">
    <el-scrollbar height="100%">
      <div v-for="(item, index) in list" :key="index" :class="{ 'role-item': true, active: item.roleId === value }" @click="handleClick(item)">
        <div v-if="item.roleId === value" class="icon">
          <el-icon><UserFilled /></el-icon>
        </div>
        <div v-else class="icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="name" :title="item.roleName">{{ item.roleName }}</div>
      </div>
    </el-scrollbar>
  </div>
</template>

<style lang="scss" scoped>
.role-picker-wrapper {
  @include rect(100%, 100%);
  border: 1px solid #e2e8ed;
  border-radius: 4px;
  .role-item {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    padding-left: 25px;
    box-sizing: border-box;
    cursor: pointer;
    .icon {
      font-size: 18px;
      margin-right: 10px;
      color: #666;
    }

    .name {
      @include ellipse();
    }
  }
  .role-item.active {
    background: var(--theme-color-light-9);
    color: var(--theme-color);
    .icon {
      color: var(--theme-color);
    }
  }
}
</style>
